#!/usr/bin/python
# -*- coding: UTF-8 -*-

import json
import os
import sys
import xml.dom.minidom

CONFIG = 'config/'
WORKDIR = 'config/workdir.json'
GAMEVERSION = '/ufd/'

config={"gamedir":"",
        "packagebuilder" : "",
        "configjson":"",
        "projectlocation" : ""
}

# 游戏列表读取操作
def getGameList(area):
    CONFIG = config["gamedir"]
    ls = []
    file = str(CONFIG + area)
    print(file)
    os.chdir(file)
    filename = os.listdir(".")
    print(file)
    for i in filename:
        portion = os.path.splitext(i)   # 把文件名拆成名字和后缀，我们只要名字
        if portion[1] == ".json":
            ls.append(portion[0])
    print(ls)
    return ls

# 游戏列表写入操作(添加的方式)
def writeGameList(filename,game):
    f = open(CONFIG + filename, "a")       # 这里是要改成utf-8编码不然默认gbl
    f.write('\n' + game)
    f.close()

# 写入配置    
def writeconfig(jsonparam,oldstr,add,filename=WORKDIR):
    old_str = str(oldstr)
    new_str = str(oldstr + add)
    print(old_str)
    print(new_str)
    file_name = filename
    key_str = jsonparam
    with open(file_name, "r+") as fp:
        file_data = ""
        modify_line = 0
        for line in fp.readlines():
            if line.find(key_str) != -1 and line.find(old_str) != -1:
                line = line.replace(old_str, new_str)
                modify_line += 1
            file_data += line

        if modify_line > 0:
            fp.seek(0, 0)
            fp.truncate()
            fp.writelines(file_data)
            return True
    return False
# 读取json存入字典
def readConfig():
    with open(WORKDIR,"r+") as f:
        temp = json.load(f)
    config["gamedir"] = temp["gamedir"]
    config["projectlocation"] = temp["projectlocation"]
    config["configjson"] = temp["configjson"]
    config["packagebuilder"] = temp["packagebuilder"]
    print(config)
    f.close()

# 读取游戏版本号
def getGameVersion(area,game):
    dom = xml.dom.minidom.parse(config["gamedir"] + area + GAMEVERSION + game +'.ufd')
    if dom :
        basedata = dom.documentElement
        print(basedata)
        strver = basedata.getAttribute("version")
        print(strver)
        version = int(strver)
        print(version)
    else:
        version = 0
    return version

# if __name__ == "__main__":
#     readConfig()
#     getGameList()
    # changeJsonParam("gamedir","1")
    # writeconfig("gamedir","D:/xinyueapp/XinYueProjJS/games")


